<template>
  <div class="aiDrawing_container">
    <van-nav-bar
			:title="$t('AI创作')"
			left-arrow
			@click-left="onClickLeft"
			@click-right="onClickRight"
		>
			<template #right>
				<van-icon name="todo-list-o" size="18" color="#ffffff"/>
			</template>
		</van-nav-bar>
		<div class="aiDrawing_container_box padding-1">
			<div class="aiDrawing_container_box_card br-16 padding-1 mb-2">
				<div class="card_title card_icon mb-0">
					<span>{{$t("画面描述")}}</span>
					<div class="card_title_icon_icon br-16">
						<span class="mr-0">{{ diamond }}</span>
						<img src="@/image/diamond/icon_ai_zs_x@1x.png" alt="">
					</div>
				</div>
				<van-field
          v-model="description"
					class="mb-1"
          type="textarea"
          rows="5"
          maxlength="100"
          :placeholder="$t('请输入画面描述')"
          show-word-limit
        />
				<div class="card_title mb-0">
					{{ $t("分辨率") }}
				</div>
				<van-dropdown-menu class="mb-1">
					<van-dropdown-item 
						v-model="resolution" 
						:options="resolutionOptions"
					/>
				</van-dropdown-menu>
				<div class="card_title mb-0">
					{{ $t("风格选择") }}
				</div>
				<van-dropdown-menu class="mb-1">
					<van-dropdown-item 
						v-model="styleSelect" 
						:options="disposeOptions"
					/>
				</van-dropdown-menu>
				<div class="card_consume" @click="diamondRecharge">
					<span class="mr-0">{{ $t("1张图消耗") + ' ' + consumeMoney }}</span>
					<img src="@/image/diamond/icon_ai_zs_x@1x.png"/>
				</div>
			</div>
			<button class="aiDrawing_container_box_btn" @click="onClickNext">
    		<span>{{ $t("下一步") }}</span>
			</button>
		</div>
		<van-image-preview v-model="previewImageShow" :images="drawingImgUrl">
		</van-image-preview>
		<div v-if="previewImageShow" class="btn_download" @click="downloadImage">{{ $t('点击下载') }}</div>
		<div class="aiDrawing_container_loadingBox" v-if="loading">
			<div v-if="timer > 0" class="loading_box">{{ timer }} s</div>
			<van-loading type="spinner" color="#fff" size="30px" />
		</div>
		<van-popup class="diamondRecharge_popup padding-1" v-model="diamondShow" closeable position="bottom" :style="{ 'min-height': '60%' }" >
			<div class="diamondRecharge_popup_header">
				<div class="header_item">
					<img src="@/image/aiQuantization/indexContent/SAT.png" alt="">
					<span class="header_item_text">{{ Number(property).toFixed(2) }}</span>
				</div>
			</div>
			<div class="diamondRecharge_popup_imgs">
				<div class="gradient-circle-container">
					<img src="@/image/diamond/pic_ai_zs_d@1x.png" class="center-image" alt="">
				</div>
			</div>
			<div class="diamondRecharge_popup_content mb-2">
				<div v-for="(item,index) in diamondList" :key="index" :class="['content_item' , activeId == item.id ? 'active' : '']" @click="activeId = item.id">
					<img src="@/image/diamond/icon_ai_zs_d@1x.png" alt="">
					<div class="content_item_num mb-0">{{item.num}}</div>
					<p class="content_item_text mb-1">{{$t('钻石')}}</p>
					<div class="content_item_price">{{Number(item.price).toFixed(2)}} SAT</div>
				</div>
			</div>
			<button @click="buyDiamond">{{$t('充值')}}</button>
		</van-popup>
  </div>
</template>

<script>
import { drawingType } from "@/utils"
import { getAiDrawParams , submitAiDraw , aiDrawCallback } from "@/request/homePage"
import { getDiamondList , diamondRecharge } from "@/request/homePage"
import { getUserInfo } from "@/request/personalCenter"
export default {
  name: "AiDrawing",
  data(){
    return{
			description: '',
			resolution: '1024*1024',
			styleSelect: "古风",
			consumeMoney: 0.44,
			consumeUnit: 'SAT',
			consumeUrl: require('@/image/aiQuantization/indexContent/SAT.png'),
			property: 8848.8848,
			previewImageShow: false,
			drawingImgUrl: [],
			resolutionOptions: [
        { text: '512*512', value: '512*512' },
        { text: '640*360', value: '640*360' },
        { text: '360*640', value: '360*640' },
        { text: '1024*1024', value: '1024*1024' },
        { text: '1280*720', value: '1280*720' },
        { text: '720*1280', value: '720*1280' },
      ],
			loading: false,
			timer: 30,
			interval: null,
			diamond: 0,
			diamondShow: false,
			diamondList: [],
			activeId: '',

			lastSubAIResult: null, // 用于存储上一次提交的AI绘画结果
    }
  },
	computed:{
		disposeOptions(){
			return drawingType.map(item => {
				return {
					text: this.$t(item.name),
					value: item.name
				}
			})
		}
	},
	mounted(){
		this.getAiDrawParams()
	},
	methods:{
		getAiDrawParams(){
			getAiDrawParams().then(res => {
				if(res.code == 1){
					this.property = res.data.sat || 0
					this.consumeMoney = res.data.price || 0
				}
			})
			this.getDiamondNum()
		},
		getDiamondNum(){
			getUserInfo().then(res=>{
				if(res.code == 1){
					this.diamond = res.data.gold || 0
				}
			})
			getDiamondList().then(res=>{
					if(res.code == 1){
						this.diamondList = res.data
					}
			})
		},
		onClickNext(){
			if(!this.description){
				this.$toast(this.$t('请输入画面描述'));
				return
			}else{
				let obj = {
					textcountent: this.description,
					imageresolution: this.resolution,
					imagestyle: this.styleSelect,
				}

				this.timer = 0
				this.loading = true;
				submitAiDraw(obj).then(res => {
					if(res.code == 1){
						this.lastSubAIResult = res.data
						this.beginGetAiDrawTimer(this.lastSubAIResult,30)
					}else{
						this.$toast.fail(res.msg)
						this.loading = false;
					}
			})
			}
		},
		getAiDrawData(obj){
			aiDrawCallback(obj).then(res => {
				// this.drawingImgUrl
				this.finishGetAiDraw()
				if(res.code == 1){
				    this.previewImageShow = true;
					this.drawingImgUrl.push(res.data.data.img)
					this.getAiDrawParams()

				}else{
					this.loading = true;
					this.beginGetAiDrawTimer(this.lastSubAIResult,15)
					this.$toast.fail('绘制进行中，请稍后')
				}
			}).catch(err => {
				this.finishGetAiDraw()
				this.$toast.fail(this.$t('下载失败'));
			});
		},

		beginGetAiDrawTimer(data,timer = 30){
			this.timer = timer;

			this.interval = setInterval(() => {
				this.timer--;
				if(this.timer == 1){
					this.getAiDrawData({id:data.data.id,taskid:data.data.taskId})
				}

				if (this.timer <= 0) {
					this.timer = 0;
				}
			}, 1000);
		},

		finishGetAiDraw() {
			if(this.interval) {
				clearInterval(this.interval);
				this.interval = null;
			}
			this.loading = false;
			this.timer = 0;
		},

		onClickLeft(){
			this.$router.go(-1)
		},
		onClickRight(){
			if(this.$route.name != 'aiDrawingHistory'){
				this.$router.push({name: 'aiDrawingHistory'})
			}
		},
		diamondRecharge(){
			// 钻石充值
			this.diamondShow = true
		},
		buyDiamond(){
			// 购买钻石
			if(this.activeId == '') return
			diamondRecharge({id: this.activeId}).then(res=>{
				if(res.code == 1){
					this.$toast.success(this.$t('充值成功'))
					this.diamondShow = false
					this.getDiamondNum()
				}
			})
		},
		downloadImage() {
			if(this.drawingImgUrl.length > 0) {
				const xhr = new XMLHttpRequest();
				xhr.open('GET', this.drawingImgUrl[0], true);
				xhr.responseType = 'blob';
				
				xhr.onload = () => {
					if (xhr.status === 200) {
						const blob = new Blob([xhr.response], {type: 'image/png'});
						const url = window.URL.createObjectURL(blob);
						const link = document.createElement('a');
						link.href = url;
						link.download = this.styleSelect + new Date().getTime() + '.png';
						link.style.display = 'none';
						document.body.appendChild(link);
						link.click();
						window.URL.revokeObjectURL(url);
						document.body.removeChild(link);
					}
				};
					
				xhr.send();
			} else {
				this.$toast(this.$t('暂无图片可下载'));
			}
		}
	},
	watch:{
		previewImageShow(newVal){
			if(newVal == false){
				location.reload();
			}
		}
	}
}
</script>

<style>

</style>